package kr.hkit.powerjava.chapter14.work;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

public class MtoK extends JFrame {

	private JPanel contentPane;
	private JPanel resultPanel;
	private InputPanel inputPanel;
	private JPanel buttonPanel;
	private JButton btnChange;
	private JTextField tfResult;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MtoK frame = new MtoK();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MtoK() {
		initialize();
	}

	private void initialize() {
		setTitle("마일을 킬로미터로 변환");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		inputPanel = new InputPanel(4);
		inputPanel.setLblNewLabel("거리를 마일 단위로 입력하시오");
		contentPane.add(inputPanel, BorderLayout.NORTH);

		buttonPanel = new JPanel();
		contentPane.add(buttonPanel, BorderLayout.CENTER);

		btnChange = new JButton("변환");
		btnChange.addActionListener(new BtnChangeActionListener());
		buttonPanel.add(btnChange);

		resultPanel = new JPanel();
		contentPane.add(resultPanel, BorderLayout.SOUTH);

		tfResult = new JTextField();
		tfResult.setHorizontalAlignment(SwingConstants.CENTER);
		resultPanel.add(tfResult);
		tfResult.setColumns(20);

		pack();
	}

	private class BtnChangeActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			if (e.getActionCommand().equals("변환")) {
				int mile = 0;
				try {
					mile = Integer.parseInt(inputPanel.getTextField());
				} catch (NumberFormatException err) {
					JOptionPane.showMessageDialog(btnChange, "정수만 가능합니다.");
					inputPanel.setTextField("");
				}
				tfResult.setText(mile + "마일은 " + mile * 1.6 + "킬로미터 입니다.");
			}
		}
	}
}
